package com.shengqin.listeners;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.read.metadata.holder.ReadRowHolder;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.shengqin.entity.SysHealthProject;
import com.shengqin.service.SysHealthProjectService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ProjectDataListener implements ReadListener<SysHealthProject> {

    private final SysHealthProjectService healthProjectService;
    private final Integer templateId;
    /**
     * 缓存的数据
     */
    private final List<SysHealthProject> cachedDataList = new ArrayList<>();

    public ProjectDataListener(SysHealthProjectService hpService, Integer pId) {
        this.healthProjectService = hpService;
        this.templateId = pId;
    }

    @Override
    public void invoke(SysHealthProject data, AnalysisContext context) {
        ReadRowHolder readRowHolder = context.readRowHolder();
        Integer rowIndex = readRowHolder.getRowIndex();
        log.info("解析到行号为{},数据:{}",rowIndex, JSON.toJSONString(data));
        cachedDataList.add(data);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
    }

    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        healthProjectService.batchSaveData(cachedDataList,templateId);
        log.info("存储数据库成功！");
    }
}
